/*
 * transLineDAO.java
 *
 * Created on February 18, 2007, 8:31 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.samlam;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Sam
 */
public class TransactionLineDAO extends BusinessObject{
    private static TransactionLineDAO instance = null;
    private static boolean memberSet = false;
    ///////////////////////////////////////
    ///   Singleton pattern
       
    /** Creates a new instance of transLineDAO */
    private TransactionLineDAO() {
    }
    
    public static synchronized TransactionLineDAO getInstance() {
        if (instance == null) {
            instance = new TransactionLineDAO();
        }
        return instance;
    }
    
    /////////////////////////////////
    ///   CREATE
    
    /**
     * There's no need for two creates because we don't need
     * a connection to create BOs.  We run the insert statement
     * later, when it get's saved for the first time.
     */
    public TransactionLine create() {//will need type and revenue source sku later
        TransactionLine tl = null;
        try{
            String id = GUID.generate();
            tl = new TransactionLine(id);
            Cache cache = Cache.getInstance();
            cache.put(tl.getId(), tl);
            
        }catch(Exception e){
            e.printStackTrace();
        }
        return tl;
    }
    
    
    /////////////////////////////////////
    ///   READ
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized TransactionLine read(String id) throws DataException {
        // check to see if id in the cache
         
        TransactionLine tl = (TransactionLine)Cache.getInstance().get(id);
        if(tl != null){
            // if so, return it immediately
            return tl;
        }
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call read with a connection (the other read method in this class)
            tl = TransactionLineDAO.getInstance().read(id, conn);
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try{
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch(SQLException e2){
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
                throw new DataException("Could not get a connection to the database.");
                
            }
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // return object
        return tl;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    synchronized TransactionLine read(String id, Connection conn) throws SQLException, DataException {
        // check again if the id is in the cache, and if so,
        // just get it from the cache.  we need to check again
        // because this method might be called directly from
        // another DAO rather than from read above.
       
        TransactionLine txl = (TransactionLine)Cache.getInstance().get(id);
        if(txl != null){
            return txl;
        }
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM transactionline WHERE transactionlineid = '"+ id + "'");
        
        //create a prepared statement
        //query the database
        //call sets from the result set
        TransactionLine tl = null;
        String memberId=null;
        if (rs.next()) {
            tl.setId(rs.getString("id"));
            tl.setRevenueSource(RevenueSourceFactory.getInstance().getDAO(rs.getString("type")).read(rs.getString("revsourceid")));
            // get any subobjects (for example, if this was the TransactionLineDAO,
            // we'd need to call the MembershipDAO to load the membership record.
            tl.setCoupon(CouponDAO.getInstance().read(rs.getString("couponid"), conn));
            Cache.getInstance().put(tl.getId(), tl);
            //RevenueSource revsource = super.create();
            /*
            RevenueSource revsource = new RevenueSource() {

                public String getDescription() {
                }
            };
             */
           // tl.setRevenueSource(revsource);//need to change when we have revenue sorces
            //tl.setRevenueSource(TransactionLineDAO.getInstance().read(rs.getString("RSTypeID"), conn));//need to change when we have revenue sorces
            tl.setTransaction(TransactionDAO.getInstance().read(rs.getString("transactionid"), conn));
            tl.setObjectAlreadyInDB(true);
            
            
            // save to the cache
            
            Cache.getInstance().put(tl.getId(), tl);
            stmt.close();
        }else{
            throw new DataException("Object was not found in the database.");
            
        }
        // return the BO
        return tl;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     */
    public synchronized void save(TransactionLine tl) throws DataException {
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call save with a connection (the other save method in this class)
            this.save(tl, conn);
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve record for id=" + tl.getId(), e);
        }
    }
    
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     * 
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the TransactionLineDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     */
    synchronized void save(TransactionLine tl, Connection conn) throws SQLException, DataException {
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (tl.isDirty()) {
            if (tl.isObjectAlreadyInDB() == true) {
                update(tl, conn);
            }else{
                insert(tl, conn);
            }
            // set the dirty flag to false now that we've saved it
            tl.setDirty(false);
            
        }
        
        // call save(bo, conn) on any subobjects (like TransactionLineDAO to MembershipDAO)
        // touch the cache for the object
        Cache.getInstance().touch(tl.getId());
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(TransactionLine tl, Connection conn) throws SQLException, DataException {
        // do the update statement
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("UPDATE transactionLine set id='"+tl.getId()+"', CouponID='"+tl.getCoupon().getId()+"', RevenueSourceID='"+tl.getRevenueSource().getId()+"', Quantity="+tl.getQuantity()+"' WHERE transactionLine_id='"+tl.getId()+"'");

        stmt.close();
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(TransactionLine tl, Connection conn) throws SQLException, DataException {
        // do the insert SQL statement
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO transactionLine VALUES ('"+tl.getId()+", "+tl.getCoupon().getId()+"', '"+tl.getRevenueSource().getId()+"', '"+tl.getQuantity()+"'");
        stmt.close();
        // tell the object that it's now in the db (so we call update next time not insert)
        tl.setObjectAlreadyInDB(true);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    // we are not supporting because we never want to delete the TransactionLine from
    // our database.
    
    
    
    //////////////////////////////
    ///  SEARCH methods
    public List<TransactionLine> readByTransactionId(String id)throws DataException{
        
        List<TransactionLine> tl = new LinkedList<TransactionLine>();
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call read with a connection (the other read method in this class)
            tl = TransactionLineDAO.getInstance().readByTransactionId(id, conn);
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try{
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch(SQLException e2){
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
                throw new DataException("Could not get a connection to the database.");
                
            }
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // return object
        return tl;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    synchronized List<TransactionLine> readByTransactionId(String id, Connection conn) throws SQLException, DataException {
        // check again if the id is in the cache, and if so,
        // just get it from the cache.  we need to check again
        // because this method might be called directly from
        // another DAO rather than from read above.
        List<TransactionLine> tlList = new LinkedList<TransactionLine>();
        
        
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM transactionline WHERE transactionid = '"+ id + "'");
        
        while(rs.next()){
        //create a prepared statement
        //query the database
        //call sets from the result set
        TransactionLine tl;
        String memberId=null;
        if (rs.next()) {
            tl = new TransactionLine(rs.getString("transline_id"));
            
            
            // get any subobjects (for example, if this was the TransactionLineDAO,
            // we'd need to call the MembershipDAO to load the membership record.
            tl.setCoupon(CouponDAO.getInstance().read(rs.getString("couponid"), conn));
            tl.setRevenueSource(RevenueSourceFactory.getInstance().getDAO(rs.getString("type")).read(rs.getString("revsourceid")));
            //tl.setRevenueSource(new RevenueSource());//need to change when we have revenue sorces
            tl.setTransaction(TransactionDAO.getInstance().read(rs.getString("transactionid"), conn));
            tl.setObjectAlreadyInDB(true);
            
            
            // save to the cache
            
            Cache.getInstance().put(tl.getId(), tl);
            stmt.close();
            tlList.add(tl);
        }else{
            throw new DataException("Object was not found in the database.");
            
        }}
        // return the BO
        return tlList;
    }

    
}